package com.demo.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.demo.entity.User;
import com.demo.service.UserService;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/list")
	List<User> selectAll(){
    	return userService.selectAll();
    }
	
	@RequestMapping("/login")
	User login(String name,String pwd,String roles,HttpSession session){
		System.out.println(name+"---"+pwd);
    	User user = userService.login(name,pwd,roles);
    	System.out.println(user.toString());
    	System.out.println(user.toString());
    	session.setAttribute("userid", user.getId());
    	return user;
    }
	
	@RequestMapping("/getloginuserinfo")
	User getloginuserinfo(HttpSession session){
		User user = new User();
		if(session.getAttribute("userid")!=null) {
			Integer id  = Integer.valueOf(String.valueOf(session.getAttribute("userid")));
	    	user =  userService.selectByPrimaryKey(id);
		}
		System.out.println(user.getId());
		return user;
    }
	
	@RequestMapping("/logout")
	int logout(HttpSession session){
		session.removeAttribute("userid");
		return 1;
    }
	
	@RequestMapping("/selectByPrimaryKey")
	User selectByPrimaryKey(int id){
		return userService.selectByPrimaryKey(id);
    }
	
	@RequestMapping("/addUser")
	int addUser(@RequestBody User user){
		int id=0;
		if(userService.findMaxId()==null) {
			id = 1;
		}else {
			id = Integer.valueOf(userService.findMaxId())+1;
		}
		user.setId(id);
		user.setDeeteflag(0);
		return userService.insert(user);
    }
	
	@RequestMapping("/modifyUserTijiao")
	int modifyUserTijiao(@RequestBody User user){
		return userService.updateByPrimaryKey(user);
    }
	
	@RequestMapping("/deleteUser")
	int deleteUser(int id){
		User user = userService.selectByPrimaryKey(id);
		if(user!=null) {
			user.setDeeteflag(1);
			return userService.updateByPrimaryKey(user);
		}else {
			return 0;
		}
    }
	
	@RequestMapping("/register")
	int register(String name,String pwd,String truename,String phone,String email,String sex,int age, String address, HttpSession session){
		int r = userService.register(name, pwd, truename, phone, email, sex, age, address);
    	System.out.println(r);
    	return r;
    }
}
